<?php
/**
 * 库存国家
 * (model)
 */
namespace App\Models\Basics;

use Illuminate\Database\Eloquent\Model;
class SysICountry extends Model
{
    protected $table = 'b_sys_i_country';

    public $timestamps = false;

    protected $guarded = [];

    public function country()
    {
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public static function options($where = [])
    {
        $query = $where ? self::query()->where(formatCondition($where)) : self::query();
        $re = $query->get()->map(function ($model){
            return collect(['country_id' => $model->country_id,
                'country' => $model->country->country ?? '']);
        });
        return $re->pluck('country','country_id');
    }

    public static function getAreaIdByCountryId($countryId){
        $areaId = self::query()->where('country_id',$countryId)->value('area_id');
        return $areaId ?: 0;
    }

    public static function getCountryIdsByAreaId($areaId){
        return self::query()->where('area_id',$areaId)->pluck('country_id');
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public static function getNaCountryIdsForNoTotalInventory(){
        return self::query()
            ->whereHas('country', function ($query){
                $query->whereIn('country',['MX','BR']);
            })
            ->pluck('country_id');
    }

    /**
     * @param $areaId
     * @return \Illuminate\Support\Collection
     */
    public static function getEuCountryIdsForNoTotalInventory($areaId){
        return self::query()
            ->where('area_id',$areaId)
            ->whereHas('country', function ($query){
                $query->whereIn('country',['NL','PL','SE','TR','BE']);
            })
            ->pluck('country_id');
    }
}
